package com.yzdbx;

import com.yzdbx.task.MainTask;
import com.yzdbx.utils.DbUtil;
import com.yzdbx.utils.GenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Hello world!
 */
public class App {

    private static final ScheduledExecutorService SCHEDULED_EXECUTOR_SERVICE = Executors.newScheduledThreadPool(1);
    private static final Logger log = LoggerFactory.getLogger(App.class);
    private static String DEL_SQL_NAME = "del.sql";

    public static void main01(String[] args) {

    }
    public static void main(String[] args) {

        //ERP业务链 销售订单 - 发货 - 出库 | 退货 - 入库


        if (GenUtil.IS_INIT.equals("N")) {
            LocalDateTime nowTime = LocalDateTime.now();
            LocalDate now = LocalDate.now();
            LocalDateTime next = LocalDateTime.parse(now + " " + GenUtil.CYCLE, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            if (next.isBefore(nowTime)) {
                next = next.plusDays(1);
            }
            long initTime = next.toInstant(ZoneOffset.ofHours(8)).toEpochMilli() - nowTime.toInstant(ZoneOffset.ofHours(8)).toEpochMilli();

            SCHEDULED_EXECUTOR_SERVICE.scheduleAtFixedRate(new MainTask(), initTime, 1000 * 60 * 60 * 24, TimeUnit.MILLISECONDS);
        } else {
            delOldData();
            new MainTask().

                    run();
        }


    }

    private static void delOldData() {
        log.info("=====================开始删除旧数据数据=========================");
        BufferedReader reader = null;
        reader = new BufferedReader(new InputStreamReader(Objects.requireNonNull(App.class.getClassLoader().getResourceAsStream(DEL_SQL_NAME)), StandardCharsets.UTF_8));
        Connection conn = DbUtil.getConnection();
        Statement stmt = null;
        try {
            stmt = conn.createStatement();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        String line;
        StringBuilder sql = new StringBuilder();

        while (true) {
            try {
                if ((line = reader.readLine()) == null) break;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            // 跳过注释和空行
            if (line.trim().isEmpty() || line.startsWith("--")) continue;
            sql.append(line);
            // 遇到分号执行语句
            if (line.trim().endsWith(";")) {
                try {
                    stmt.execute(sql.toString());
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
                sql.setLength(0);
            }
        }
        try {
            conn.commit();
            DbUtil.closeConnection(conn);
            reader.close();
            stmt.close();
        } catch (IOException | SQLException e) {
            throw new RuntimeException(e);
        }
        log.info("=====================删除旧数据数据成功=========================");
    }
}
